#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <memory>
#include "Thread.hpp"

uint16_t ServerPort = 0;
std::string ServerIP;

static void Usage(std::string proc)
{
    std::cout << "\nUsage: " << proc << " ServerIP ServerPort" << std::endl;
}

// 写线程
static void* UdpSend(void* args)
{
    ThreadData* td = (ThreadData*)args;
    int sock = *(int*)td->_args;

    std::string message;
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(ServerIP.c_str());
    server.sin_port = htons(ServerPort);

    while(true)
    {
        std::cerr << "Please Enter Your Message: ";
        std::getline(std::cin, message);
        if(message == "quit") break;
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));
    }

    return nullptr;
}

// 读线程
static void* UdpRecv(void* args)
{
    ThreadData* td = (ThreadData*)args;
    int sock = *(int*)td->_args;
    std::string threadName = td->_name;

    char buffer[1024];
    while(true)
    {
        memset(buffer, sizeof buffer, 0);
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t s = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&temp, &len);
        if(s > 0)
        {
            buffer[s] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return nullptr;
}


int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    // 1. 创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if(sock < 0)
    {
        std::cerr << "Socket Error!" << std::endl;
        exit(2);
    }

    ServerIP = argv[1];
    ServerPort = atoi(argv[2]);

    // 读线程和写线程都不会修改端口号,所以不需要进行加锁保护
    // 读写进程使用的是同一个端口号sock,sock是文件描述符
    // 说明Udp是全双工的(可以同时进行读写且不受干扰)
    std::unique_ptr<Thread> Sender(new Thread(1, UdpSend, (void*)&sock));
    std::unique_ptr<Thread> Recver(new Thread(2, UdpRecv, (void*)&sock));
    // 创建写线程和读线程
    Sender->Create();
    Recver->Create();
    // 等待写线程和读线程
    Sender->Join();
    Recver->Join();

    close(sock);

    return 0;
}